//
//  CommentDetailViewController.m
//  lvtu
//
//  Created by Apple on 12-6-28.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CommentDetailViewController.h"
#import "wxAppDelegate.h"

@interface CommentDetailViewController ()

@end

@implementation CommentDetailViewController
@synthesize msgInfo;
@synthesize reloading=_reloading;
@synthesize refreshHeaderView;
@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithMsgInfo:(MessageInfo*) info
{
    self = [super init];
    if (self) {
        self.msgInfo = info;
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    [titleLabel setText:[NSString stringWithFormat:@"评论(%@)",msgInfo.commentcount]];
    [titleLabel setBackgroundColor:[UIColor clearColor]];
    [titleLabel setTextAlignment:UITextAlignmentCenter];
    [titleLabel setTextColor:[UIColor colorWithRed:111/255.0 green:117/255.0 blue:81/255.0 alpha:1.0]];
    [titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
    self.navigationItem.titleView = titleLabel;
    [titleLabel release];
    titleLabel = nil;
    
    UIImage* backImage = [UIImage imageNamed:@"btn_back_normal.png"];
    UIButton* backbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    backbutton.frame = CGRectMake(0, 0, backImage.size.width, backImage.size.height);
    [backbutton setBackgroundImage:backImage forState:UIControlStateNormal];
    [backbutton setBackgroundImage:[UIImage imageNamed:@"btn_back_press.png"] forState:UIControlStateHighlighted];
    [backbutton addTarget:self action:@selector(backButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbutton];
    self.navigationItem.leftBarButtonItem = backButtonItem;
    [backButtonItem release];
    
    m_ShowAry = [[NSMutableArray alloc] init];
    //    for (int i = 0 ; i < 6; i++) {
    //        MessageInfo* messageInfo = [[MessageInfo alloc] init];
    //        [m_ShowAry addObject:messageInfo];
    //        [messageInfo release];
    //    }
    
    nodataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    nodataLabel.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2-50);
    nodataLabel.text = @"无评论";
    nodataLabel.backgroundColor = [UIColor clearColor];
    nodataLabel.hidden = YES;
    [self.view addSubview:nodataLabel];
    
    int addHeight = 0;
    if (self.view.frame.size.height > 480)
    {
        addHeight += 80;
    }
    if ([wxAppDelegate getAppDelegate].isLogin == NO) {
        m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(16, 27, 338, 285+addHeight) style:UITableViewStylePlain];
    }
    else
    {
        m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(16, 27, 288, 285+addHeight) style:UITableViewStylePlain];
    }
    m_tableView.delegate = self;
    m_tableView.dataSource = self;
    //[self.view addSubview:m_tableView];
    
    UIImageView* inputView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, m_tableView.backgroundView.frame.size.width, m_tableView.backgroundView.frame.size.height)];
    UIImage* stretchImg = [[UIImage imageNamed:@"bg_whiteframe.png"] stretchableImageWithLeftCapWidth:30 topCapHeight:20];
    inputView.image = stretchImg;   
    inputView.clipsToBounds = YES;
    inputView.userInteractionEnabled = YES;
    [m_tableView.backgroundView addSubview:inputView];
    [inputView release];
    
    if (refreshHeaderView == nil) {
        refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - m_tableView.bounds.size.height, 320.0f, m_tableView.bounds.size.height)];
        refreshHeaderView.backgroundColor = [UIColor colorWithRed:232.0/255.0 green:235.0/255.0 blue:212.0/255.0 alpha:1.0];
        refreshHeaderView.bottomBorderThickness = 1.0;
        [m_tableView addSubview:refreshHeaderView];
        m_tableView.showsVerticalScrollIndicator = YES;
        [refreshHeaderView release];
    }
    
    //创建页脚button
    footSpinnerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 288, 40)];
    UIButton* footButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [footButton setFrame:CGRectMake(0, 0, 288, 40)];
    [footButton setTitle:@"更多"forState:UIControlStateNormal];
    [footButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [footButton addTarget:self action:@selector(footButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    [footButton addTarget:self action:@selector(footButtonTouchDown:) forControlEvents:UIControlEventTouchDown];
    [footSpinnerView addSubview:footButton];
    m_tableView.tableFooterView = footSpinnerView;
    
    commentBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 305, 320, 60)];
    commentBackgroundView.backgroundColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:0.9];
    if ([wxAppDelegate getAppDelegate].isLogin) {
        [self.view addSubview:commentBackgroundView];
    }
    
    contentTextField = [[UITextField alloc] init];
    UIImage* TextFieldImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_imput.png" ofType:nil]];
    [contentTextField setFrame:CGRectMake(5, 5, 240, 45)];
    [contentTextField setBackground:TextFieldImage];
    contentTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;                
    [contentTextField setAutocorrectionType:UITextAutocorrectionTypeDefault];
    [contentTextField setReturnKeyType:UIReturnKeyDefault];
    [contentTextField setFont:[UIFont boldSystemFontOfSize:12]];
    [contentTextField setDelegate:self];
    [contentTextField setTextColor:[UIColor grayColor]];
    [contentTextField setPlaceholder:@""];
    [contentTextField setKeyboardType:UIKeyboardTypeDefault];
    [contentTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [contentTextField setClipsToBounds:YES];
    [commentBackgroundView addSubview:contentTextField];
    [contentTextField release];
    
    UIButton* commentbutton = [UIButton buttonWithType:UIButtonTypeCustom];
	commentbutton.frame = CGRectMake(250, 5, 60, 45);
    [commentbutton setBackgroundImage:[UIImage imageNamed:@"btn_done_normal.png"] forState:UIControlStateNormal];
    [commentbutton setBackgroundImage:[UIImage imageNamed:@"btn_done_press.png"] forState:UIControlStateHighlighted];
    [commentbutton setTitle:@"评论" forState:UIControlStateNormal];
	[commentbutton addTarget:self action:@selector(commentbuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[commentBackgroundView addSubview:commentbutton];
    
    NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:msgInfo.travellineid,@"c_travel_line_id",nil];
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = COMMENTLIST;
    msg.ui_delegate = self;
    
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_line_comment_list" postInfo:info userInfo:msg];
    
    baseAlert = [[UIAlertView alloc] initWithTitle:@"正在加载..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [baseAlert show];
    
    UIActivityIndicatorView* aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    aiv.center = CGPointMake(baseAlert.bounds.size.width/2.0f, baseAlert.bounds.size.height-40.0f);
    [aiv startAnimating];
    [baseAlert addSubview:aiv];
    [aiv release];
    
    pageIndex = 1;
	// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [baseAlert release];
    [footSpinnerView release];
    [nodataLabel release]; nodataLabel = nil;
    [m_ShowAry removeAllObjects];
    [m_ShowAry release]; m_ShowAry = nil;
    [m_tableView release]; m_tableView = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

- (void)backButtonPress:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)commentbuttonPressed:(id)sender
{
    if ([contentTextField.text isEqualToString:@""]) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入评论内容！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        return;
    }
    NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:msgInfo.travellineid,@"c_travel_line_id",contentTextField.text,@"content",nil];
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = COMMENTTRAVEL;
    msg.ui_delegate = self;
    
    [contentTextField resignFirstResponder];
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=do_create_line_comment" postInfo:info userInfo:msg];
    [delegate sendCommentSuccess];
}

- (void)touchUpCommentDetailCellButton:(NSInteger)index
{
    NSDictionary* info = [m_ShowAry objectAtIndex:index];
    [contentTextField setPlaceholder:[NSString stringWithFormat:@"回复:%@",[info objectForKey:@"name"]]];
}

#pragma -mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [contentTextField setText:@""];
    [contentTextField setTextColor:[UIColor blackColor]];
    
    [commentBackgroundView setFrame:CGRectMake(0, 0, 320, 60)];
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [contentTextField resignFirstResponder];
    [commentBackgroundView setFrame:CGRectMake(0, 318, 320, 60)];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (1 == range.length) {//按下回格键
        return YES;
    }
    
    if ([string isEqualToString:@"\n"])
    {//按下return键
        //这里隐藏键盘，不做任何处理
        [textField resignFirstResponder];
        //        [self willLoginWeibo];
        return NO;
    }
    else
    {
        return YES;
    }
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == contentTextField)
    {
        [contentTextField setText:@""];
        [contentTextField setPlaceholder:@""];
        [contentTextField setTextColor:[UIColor grayColor]];
    }
    return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [m_ShowAry count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CommentDetailCell";
    
    CommentDetailCell *cell = (CommentDetailCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[CommentDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    [cell updateCommentDetail:[m_ShowAry objectAtIndex:indexPath.row] Index:indexPath.row];
    cell.delegate = self;
    // Configure the cell...
    //    [cell setVideoCell:[m_ShowAry objectAtIndex:indexPath.row]:self.tableView];
    //    cell.cellProfilePic.delegate = self;
    //    [cell.cellProfilePic setM_row:indexPath.row];
    //    cell.cellContentPic.delegate = self;
    //    [cell.cellContentPic setM_row:indexPath.row];
    return cell;
}

#pragma mark - buttonaction

//button点下改变背景色的效果
-(void)footButtonTouchDown:(id)button;
{
    [button setBackgroundColor:[UIColor blueColor]];
}

//处理button抬起消息
- (void)footButtonTouchUpInside:(id)button
{
    [button setBackgroundColor:[UIColor clearColor]];
    
    //从数据库中每次多获取最新的20条微博,放入model后加入数组
    //    NSArray* ary = [[NSArray alloc] initWithArray:[database getStatusesData:[m_ShowArycount]+20]];
//    [m_ShowAry removeAllObjects];
    //    for (int i = 0; i < [ary count]; i++) {
    //        NSDictionary* dict =  [databasegetUserData:[[ary objectAtIndex:i] objectForKey:@"user"]];
    //        StatusInfo* statusInfo = [[StatusInfoalloc] initWithDictionary:[ary objectAtIndex:i] :dict];
    //        [m_ShowAryaddObject:statusInfo];
    //        [statusInfo release];
    //    }
    //    [ary release];
    
    //刷新界面，判断是否显示foot
    //    [self.tableViewreloadData];
    //    if ([databasegetStatusCount] <= [m_ShowArycount]) {
    //        self.tableView.tableFooterView.hidden = YES;
    //    }
    NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:msgInfo.travellineid,@"c_travel_line_id",[NSString stringWithFormat:@"%d",pageIndex+1],@"page",nil];
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = COMMENTLIST;
    msg.ui_delegate = self;
    
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_line_comment_list" postInfo:info userInfo:msg];
    [baseAlert show];
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    //[tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"index = %d",indexPath.row);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    //    self.tableView.delegate = nil;
    //    StatusCell *cell = (StatusCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    //    self.tableView.delegate = self;
    //    return cell.cellHeight;
    NSDictionary* info = [m_ShowAry objectAtIndex:indexPath.row];
    NSString* content = [info objectForKey:@"content"];
    CGFloat tempHeight = [content sizeWithFont:[UIFont systemFontOfSize:12.0f]
                         constrainedToSize:CGSizeMake(160, 9999) lineBreakMode:UILineBreakModeCharacterWrap].height;
    if (tempHeight < 35.0) {
        return 70.0;
    }
    else {
        return tempHeight + 35.0;
    }
}

#pragma mark - ScrollView callbacks
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{	
	if (scrollView.isDragging) {
		if (refreshHeaderView.state == EGOOPullRefreshPulling && scrollView.contentOffset.y > -65.0f && scrollView.contentOffset.y < 0.0f && !_reloading) {
			[refreshHeaderView setState:EGOOPullRefreshNormal];
		} else if (refreshHeaderView.state == EGOOPullRefreshNormal && scrollView.contentOffset.y < -65.0f && !_reloading) {
			[refreshHeaderView setState:EGOOPullRefreshPulling];
		}
	}
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{	
    NSLog(@"Scroll view offset: %f", scrollView.contentOffset.y);
    
	if (scrollView.contentOffset.y <= - 65.0f && !_reloading) {
		_reloading = YES;
		[refreshHeaderView setState:EGOOPullRefreshLoading];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.2];
		m_tableView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
		[UIView commitAnimations];
        [self reloadTableViewDataSource];
	}
}

#pragma mark - RefreshHeaderView methods
- (void)dataSourceDidFinishLoadingNewData:(NSNumber *)loadedData
{	
	_reloading = NO;
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.3];
	[m_tableView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
	[UIView commitAnimations];
	
	[refreshHeaderView setState:EGOOPullRefreshNormal];
    
}

- (void)reloadTableViewDataSource
{
	NSLog(@"Please override reloadTableViewDataSource.");
    [self dataSourceDidFinishLoadingNewData:nil];
}

- (void)dataSourceDidFailPresentingError
{
    NSLog(@"Please implement your own UIAlert view.");
}

#pragma -mark DataSourceDelegate

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
    [m_ShowAry removeAllObjects];
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
    if ([coreMsg.data isEqual: COMMENTLIST]) {
        nodataLabel.hidden = YES;
        CommentList* commentList = (CommentList*)data;
        pageIndex = commentList.currentPageId;
        if (commentList.totlePageCount && commentList.totlePageCount > 1) {
            m_tableView.tableFooterView = footSpinnerView;
        }
        else {
            m_tableView.tableFooterView = nil;
        }
        for (int i = 0 ; i < [commentList.commentArray count]; i++) {
            [m_ShowAry addObject:[commentList.commentArray objectAtIndex:i]];
        }
        if (![m_tableView isDescendantOfView:self.view]) {
            [self.view addSubview:m_tableView];
            [self.view bringSubviewToFront:commentBackgroundView];
        }
        [m_tableView reloadData];
        [self dataSourceDidFinishLoadingNewData:nil];
    }
    if ([coreMsg.data isEqual: COMMENTTRAVEL]) {
        NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:msgInfo.travellineid,@"c_travel_line_id",nil];
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = COMMENTLIST;
        msg.ui_delegate = self;
        
        [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_line_comment_list" postInfo:info userInfo:msg];
    }
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
    if ([coreMsg.data isEqual: COMMENTLIST]) {
        nodataLabel.hidden = NO;
        m_tableView.tableFooterView = nil;
        //        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:data delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        //        alert.tag = 2001;
        //        [alert show];
        //        [alert release];
        [self dataSourceDidFinishLoadingNewData:nil];
    }
    else if ([coreMsg.data isEqual: COMMENTTRAVEL]){
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"评论失败啦！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

@end
